package com.hurl.waguji.base;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.xwork.StringUtils;

import com.hurl.waguji.biz.Constants;

public class SqlReader {
	private static Properties templates = buildConfiguration();
	
	public static String getSql(String sqlId,Object[] args){
		String sql = templates.getProperty(sqlId);
		if(StringUtils.isEmpty(sql)){
			return null;
		}
		if(args!=null && args.length>0){
			for(int i=0;i<args.length;i++){
				sql = sql.replaceFirst("\\?", String.valueOf(args[i]));
			}
		}
		return sql;
	}
	public static String getSql(String sqlId){
		return templates.getProperty(sqlId);
	}
	public static String getSql(String sqlId,Object arg){
		return getSql(sqlId,new Object[]{arg});
	}
	private static Properties buildConfiguration(){
		Properties props = new Properties();
		InputStream is = ConfigHelper.getResourceAsStream( "/"+Constants.SQL_CONFIG_FILE);
		try {
			props.load(is);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WagujiRuntimeException(e.getMessage(),e);
		}
		return props;
	}
	
	
}
